package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket=null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    ExecutorService executorService= Executors.newCachedThreadPool();
    public void start() throws IOException {
        System.out.println("server start!");
        while (true){
            //首先接收客户端的连接，才能进行通信
            //如果有客户端和服务器建立起了链接，accept能返回
            //否则阻塞
            Socket socket=serverSocket.accept();
            //通过这个方法完成后续客户端的整个连接过程
            //processConnection(socket); 这种写法不能实现多客户端访问服务器的效果
            //用多线程可以达到这种效果
//            Thread t=new Thread(()->{
//                processConnection(socket);
//            });     //当线程多了，效果也不好了，这时可以用线程池
//            t.start();
            executorService.submit(()->{
                processConnection(socket);
            });
        }

    }

    private void processConnection(Socket socket) {
        //在一次连接中，客户端和服务器可能进行多组数据传输
        System.out.printf("[%s:%d] 客户端上线!\n",socket.getInetAddress(),socket.getPort());
        //通过socket.getInputStream和socket.getOutputStream这两个操作，就拿到了socket里面内置的两个流对象，之后读也是从socket里面读，写也是写入socket里面去
        try (InputStream inputStream=socket.getInputStream();
             OutputStream outputStream=socket.getOutputStream()){
            Scanner scanner=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);
              while (true){
                  //处理多次请求/响应的读写操作
                  //每次循环就是处理一次的读写操作
                  if(!scanner.hasNext()){
                      System.out.printf("[%s:%d] 客户端下线!\n",socket.getInetAddress(),socket.getPort());
                      break;
                  }
                  //1.读取请求，并解析（直接scanner.next()读取内容，并转化为字符串）
                String request=scanner.next();
                  //2.计算请求响应
                  String response=process(request);
                  //3.将响应传回客户端
                  writer.println(response);
                  writer.flush();
                  //4.打印日志
                  System.out.printf("[%s:%d] req: %s ,resp：%s\n",socket.getInetAddress(),socket.getPort(),request,response);
              }
        }catch (IOException e ){
            e.printStackTrace();
        }
    }

   public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer=new TcpEchoServer(10009);
        tcpEchoServer.start();
    }
}
